/**
 * 会员充值工具函数
 */

// 会员类型配置
export const MEMBER_TYPES = {
  normal: {
    id: 'normal',
    name: '普通会员',
    price: 1,
    description: '下单即可得返利现金',
    benefits: ['返利现金', '专属优惠', '优先客服']
  },
  premium: {
    id: 'premium',
    name: '高级会员',
    price: 10,
    description: '享受更多专属权益',
    benefits: ['返利现金', '专属优惠', '优先客服', '免费配送', '生日特权']
  },
  vip: {
    id: 'vip',
    name: 'VIP会员',
    price: 50,
    description: '尊享VIP专属服务',
    benefits: ['返利现金', '专属优惠', '优先客服', '免费配送', '生日特权', '专属客服', '积分加速']
  }
};

// 获取会员类型列表
export function getMemberTypes() {
  return Object.values(MEMBER_TYPES);
}

// 根据ID获取会员类型
export function getMemberTypeById(id) {
  return MEMBER_TYPES[id] || MEMBER_TYPES.normal;
}

// 计算会员价格
export function calculateMemberPrice(memberTypeId) {
  const memberType = getMemberTypeById(memberTypeId);
  return memberType.price;
}

// 格式化价格显示
export function formatPrice(price) {
  return `¥${parseFloat(price).toFixed(2)}`;
}

// 显示会员选择提示
export function showMemberSelectionToast(memberName) {
  uni.showToast({
    title: `已选择${memberName}`,
    icon: 'success',
    duration: 1500
  });
}

// 显示支付确认对话框
export function showPaymentConfirm(amount, memberName) {
  return new Promise((resolve) => {
    uni.showModal({
      title: '确认支付',
      content: `确认支付 ${formatPrice(amount)} 开通${memberName}？`,
      success: (res) => {
        resolve(res.confirm);
      },
      fail: () => {
        resolve(false);
      }
    });
  });
}

// 模拟支付过程
export function processPayment(amount, memberName) {
  return new Promise((resolve) => {
    uni.showLoading({
      title: '支付中...'
    });
    
    setTimeout(() => {
      uni.hideLoading();
      uni.showToast({
        title: '支付成功！',
        icon: 'success',
        duration: 2000
      });
      
      // 保存会员信息到本地存储
      saveMemberInfo(memberName);
      
      resolve(true);
    }, 2000);
  });
}

// 保存会员信息到本地存储
export function saveMemberInfo(memberName) {
  try {
    const memberInfo = {
      name: memberName,
      joinDate: new Date().toISOString(),
      status: 'active'
    };
    uni.setStorageSync('member_info', JSON.stringify(memberInfo));
  } catch (e) {
    console.error('保存会员信息失败:', e);
  }
}

// 从本地存储获取会员信息
export function getMemberInfo() {
  try {
    const memberData = uni.getStorageSync('member_info');
    return memberData ? JSON.parse(memberData) : null;
  } catch (e) {
    console.error('获取会员信息失败:', e);
    return null;
  }
}

// 检查是否为会员
export function isMember() {
  const memberInfo = getMemberInfo();
  return memberInfo && memberInfo.status === 'active';
}

// 获取会员权益列表
export function getMemberBenefits(memberTypeId) {
  const memberType = getMemberTypeById(memberTypeId);
  return memberType.benefits || [];
}

// 显示会员权益详情
export function showMemberBenefits(memberTypeId) {
  const benefits = getMemberBenefits(memberTypeId);
  const memberType = getMemberTypeById(memberTypeId);
  
  uni.showModal({
    title: `${memberType.name}权益`,
    content: benefits.join('\n'),
    showCancel: false,
    confirmText: '知道了'
  });
}

// 验证支付金额
export function validatePaymentAmount(amount) {
  if (amount <= 0) {
    uni.showToast({
      title: '支付金额必须大于0',
      icon: 'none',
      duration: 2000
    });
    return false;
  }
  return true;
}

// 处理支付错误
export function handlePaymentError(error) {
  console.error('支付错误:', error);
  uni.showToast({
    title: '支付失败，请重试',
    icon: 'none',
    duration: 2000
  });
}

// 获取推荐会员类型
export function getRecommendedMemberType() {
  // 这里可以根据用户行为数据推荐合适的会员类型
  return MEMBER_TYPES.normal;
}

// 计算会员折扣
export function calculateMemberDiscount(originalPrice, memberTypeId) {
  const memberType = getMemberTypeById(memberTypeId);
  let discountRate = 0;
  
  switch (memberTypeId) {
    case 'normal':
      discountRate = 0.05; // 5%折扣
      break;
    case 'premium':
      discountRate = 0.10; // 10%折扣
      break;
    case 'vip':
      discountRate = 0.15; // 15%折扣
      break;
    default:
      discountRate = 0;
  }
  
  return originalPrice * discountRate;
}

// 格式化会员到期时间
export function formatMemberExpiryDate(expiryDate) {
  if (!expiryDate) return '永久有效';
  
  const date = new Date(expiryDate);
  const now = new Date();
  const diffTime = date.getTime() - now.getTime();
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  
  if (diffDays <= 0) {
    return '已过期';
  } else if (diffDays <= 7) {
    return `剩余${diffDays}天`;
  } else {
    return date.toLocaleDateString();
  }
} 